<template>
  <Wrapper>
    <el-card shadow="never">
      <el-row>
        <el-space wrap>
          <el-select
            v-model="type"
            placeholder="请选择生成类型"
            style="width: 200px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button
            type="primary"
            @click="saveAsImage"
          >点击生成图片</el-button>
          <el-button
            type="primary"
            @click="downloadPoster"
          >生成图片并下载</el-button>
        </el-space>
      </el-row>

      <el-divider />
      <div ref="posterEl">
        <div>121212121</div>
        <img
          src="@/assets/images/logo.png"
          style="width: 200px; height: 200px;"
        />
        <icon
          name="Edit"
          color="red"
          size="30"
        />
      </div>

      <modal
        v-model="visible"
        title="图片预览"
        @close="close"
      >
        <img
          :src="imageUrl"
          style="width: 100%; height: 100%;"
        >
      </modal>
    </el-card>
  </Wrapper>
</template>

<script setup>
import { useTemplateRef } from 'vue'
import * as methods from 'modern-screenshot'

const route = useRoute()
const el = useTemplateRef('posterEl')

const imageUrl = ref('')
const type = ref('Png')
const visible = ref(false)
const options = [
  { label: 'png', value: 'Png' },
  { label: 'svg', value: 'Svg' },
  { label: 'jpeg', value: 'Jpeg' },
  { label: 'webp', value: 'Webp' },
  { label: 'DataUrl', value: 'DataUrl' },
  { label: 'blob', value: 'Blob' },
]

async function saveAsImage() {
  // // FIXME: mac像素密度是普通屏幕的两倍
  const res = await methods[`domTo${type.value}`](el.value, { scale: 2 })
  console.log(res)
  imageUrl.value = res
  visible.value = true
}

async function downloadPoster() {
  const download = (url) => {
    const a = document.createElement('a')
    a.href = url
    a.download = route.path.split('/').at(-1) + '.jpg'
    a.click()
    a.remove()
  }
  if (!imageUrl.value) {
    const res = await methods[`domTo${type.value}`](el.value, { scale: 2 })
    imageUrl.value = res
    download(res)
    return
  }
  download(imageUrl.value)
}

function close() {
  imageUrl.value = ''
  visible.value = false
}
</script>
